import 'dart:async';

import 'package:flutter/material.dart';
import 'package:macless_haystack/preferences/user_preferences_model.dart';
import 'package:provider/provider.dart';
import 'package:macless_haystack/accessory/accessory_detail.dart';
import 'package:macless_haystack/accessory/accessory_icon.dart';
import 'package:macless_haystack/accessory/no_accessories.dart';
import 'package:macless_haystack/item_management/item_export.dart';
import 'package:macless_haystack/accessory/accessory_registry.dart';
import 'package:intl/intl.dart';
import 'package:scrollview_observer/scrollview_observer.dart';

class KeyManagement extends StatefulWidget {
  const KeyManagement({super.key});

  @override
  State<StatefulWidget> createState() {
    return _KeyManagementState();
  }
}

class _KeyManagementState extends State<KeyManagement>
    with SingleTickerProviderStateMixin {
  /// Displays a list of all accessories.
  ///
  /// Each accessory can be exported and is linked to a detail page.
  final ScrollController _scrollController = ScrollController();
  late ListObserverController observerController;

  late StreamSubscription<JumpToListItemEvent> jumpToListener;

  late AnimationController _blinkController;
  String _blinkAccessoryId = '';

  @override
  void initState() {
    super.initState();

    _blinkController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 300),
    )..repeat(reverse: true, period: Duration(milliseconds: 600));

    observerController = ListObserverController(controller: _scrollController);

    var accessoryRegistry =
        Provider.of<AccessoryRegistry>(context, listen: false);

    jumpToListener =
        accessoryRegistry.eventBus.on<JumpToListItemEvent>().listen((event) {
      if (event.tabIdx == 1) {
        observerController.jumpTo(index: event.itemIdx);
        setState(() {
          _blinkAccessoryId = accessoryRegistry.accessories2[event.itemIdx].id;
        });
        Future.delayed(Duration(milliseconds: 1200), () {
          setState(() {
            _blinkAccessoryId = '';
          });
        });
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((_) {
      var accessoriesCount = accessoryRegistry.accessories.length;
      if (accessoriesCount > 1) {
        if (mounted) {
          _showFirstTimeHint();
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AccessoryRegistry>(
      builder: (context, accessoryRegistry, child) {
        var accessories = accessoryRegistry.accessories2;

        if (accessories.isEmpty) {
          return const NoAccessoriesPlaceholder();
        }

        return Scrollbar(
            child: ListViewObserver(
          controller: observerController,
          child: ReorderableListView(
            onReorder: (int oldIndex, int newIndex) {
              setState(() {
                if (newIndex > oldIndex) newIndex--;
                final item = accessories.removeAt(oldIndex);
                accessories.insert(newIndex, item);
                accessoryRegistry.saveAccessories();
              });
            },
            scrollController: _scrollController,
            children: accessories.map((accessory) {
              String lastSeen = accessory.datePublished != null &&
                      accessory.datePublished != DateTime(1970)
                  ? DateFormat('yyyy-MM-dd HH:mm')
                      .format(accessory.datePublished!)
                  : '无';
              return Material(
                  key: ValueKey(accessory.id), // 必须提供唯一的key
                  child: AnimatedBuilder(
                      animation: _blinkController,
                      builder: (context, child) {
                        return Opacity(
                          opacity: accessory.id == _blinkAccessoryId
                              ? _blinkController.value
                              : 1.0,
                          child: child,
                        );
                      },
                      child: ListTile(
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => AccessoryDetail(
                                      accessory: accessory,
                                    )),
                          );
                          observerController.jumpTo(index: 0);
                        },
                        dense: true,
                        title: Text(accessory.name),
                        subtitle: Text('最近一次出现: $lastSeen'),
                        leading: AccessoryIcon(
                          icon: accessory.icon,
                          color: accessory.color,
                        ),
                        trailing: ItemExportMenu(accessory: accessory),
                      )));
            }).toList(),
          ),
        ));
      },
    );
  }

  void _showFirstTimeHint() async {
    var userPreferences = Provider.of<UserPreferences>(context, listen: false);
    bool hasShownHint = userPreferences.getBool('DRAG_SORT_HINT') ?? false;
    if (!hasShownHint) {
      var text = '';
      switch (Theme.of(context).platform) {
        case TargetPlatform.linux:
        case TargetPlatform.windows:
        case TargetPlatform.macOS:
          text = '列表长按图标=可拖拽排序';
        case TargetPlatform.iOS:
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
          text = '列表长按可拖拽排序';
      }

      // 显示SnackBar提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: [
              Icon(Icons.info, color: Colors.white),
              SizedBox(width: 12),
              Expanded(
                child: Text(text),
              ),
            ],
          ),
          backgroundColor: Colors.blue,
          duration: Duration(days: 1),
          action: SnackBarAction(
            label: '知道了',
            textColor: Colors.white,
            onPressed: () {},
          ),
        ),
      );
      await userPreferences.setBool('DRAG_SORT_HINT', true);
    }
  }

  @override
  void dispose() {
    jumpToListener.cancel();
    _blinkController.dispose();
    observerController.controller?.dispose();
    super.dispose();
  }
}
